package com.qqpz.sign_project.service.impl;

import com.qqpz.sign_project.entity.Location;
import com.qqpz.sign_project.mappers.LocationMapper;
import com.qqpz.sign_project.service.LocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class LocationServiceImpl implements LocationService {
    @Autowired
    private LocationMapper locationMapper;
    @Override
    public List<Location> queryAll() {
        return locationMapper.queryAll();
    }

    @Override
    public List<Location> queryByXY(Double x, Double y) {
        List<Location> list = locationMapper.queryAll();
        List<Map<String,Object>> mapList=new ArrayList<>();
        for (Location l:
             list) {
            Map<String,Object> map=new HashMap<>();
            map.put("location",l);
            double r = Math.sqrt(l.getLocationX()-x)*(l.getLocationX()-x)+(l.getLocationY()-y)*(l.getLocationY()-y);
            map.put("r",r);
            mapList.add(map);
        }
        mapList.sort(Comparator.comparingDouble(o->Double.parseDouble(o.get("r").toString())));
        List<Location> res=new ArrayList<>();
        for (int i=0;i<8&&i<mapList.size();i++){
            res.add((Location) mapList.get(i).get("location"));
        }
        return res;
    }

    @Override
    public List<Location> queryByName(String name) {
        return locationMapper.queryByName(name);
    }

    @Override
    public Location queryById(String id) {
        return locationMapper.queryById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int createLocation(Location location) {

        return locationMapper.createLocation(location);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateLocation(Location location) {
        return locationMapper.updateLocation(location);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteLocation(String id) {
        return locationMapper.deleteLocation(id);
    }
}
